package com.htiiot.tools;

import com.htiiot.config.Configs;
import org.apache.commons.cli.*;
import org.apache.log4j.Logger;

import java.io.IOException;

public class Cmd {
    private static Logger log = Logger.getLogger(Cmd.class);
    public static void parseCmd(String[] args) throws IOException {
        Options options = new Options();
        options.addOption("h", "help", false, "Print this usage information");
        options.addOption("hp","hdfs.path",true,null);
        options.addOption("hrp","hdfs.root.psth",true,"The root of log in HDFS System");
        options.addOption("bs","bootstrap.server",true,"kafka bootstrap server");
        options.addOption("gi","group.id",true,"The group id for kafka");
        options.addOption("tp","topic",true,"The topic of kafka");
        CommandLine cmd = null;
        CommandLineParser parser = new BasicParser();
        ProUtil proUtil = ProUtil.getInstance();
        boolean change = false;
        try {
            cmd = parser.parse(options, args);
        } catch (org.apache.commons.cli.ParseException e1) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("log2hdfs", options);
            e1.printStackTrace();
            System.exit(0);
        }
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("log2hdfs", options);
            System.exit(0);
        }
        if (cmd.hasOption("hp")) {
            Configs.HdfsConfig.HDFS_PATH = cmd.getOptionValue("hp");
            change = true;
            proUtil.set("hdfs.path",cmd.getOptionValue("hp"));
        }
        if (cmd.hasOption("hrp")) {
            Configs.HdfsConfig.HDFS_ROOT_PATH = cmd.getOptionValue("hrp");
            change = true;
            proUtil.set("hdfs.root.path",cmd.getOptionValue("hrp"));
        }
        if (cmd.hasOption("bs")) {
            Configs.KafkaConfig.BOOTSTRAP = cmd.getOptionValue("bs");
            change = true;
            proUtil.set("bootstrap.server",cmd.getOptionValue("bs"));
        }
        if (cmd.hasOption("gi")) {
            Configs.KafkaConfig.GROUPID = cmd.getOptionValue("gi");
            change = true;
            proUtil.set("group.id",cmd.getOptionValue("gi"));
        }
        if (cmd.hasOption("tp")) {
            Configs.KafkaConfig.TOPIC = cmd.getOptionValue("tp");
            change = true;
            proUtil.set("topic",cmd.getOptionValue("tp"));
        }
        if(change){
            log.info("Cmd line has param in,saving param into config file...");
            proUtil.store();
            log.info("Saving Success!.\r\n"+proUtil.getPro().toString());
        }
    }
}